package cc.facesign.acl.service.impl;

import cc.facesign.acl.service.AclMenuService;
import cc.facesign.acl.service.TblUserService;
import cc.facesign.common.exception.FacesignException;
import cc.facesign.common.utils.bean.R;
import cc.facesign.security.bean.LoginUser;
import cc.facesign.security.bean.TblUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private TblUserService userService;

    @Autowired
    private AclMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LambdaQueryWrapper<TblUser> w = new LambdaQueryWrapper<>();
        w.eq(TblUser::getPhone, s);

        TblUser user = userService.getOne(w);
        if (user == null) {
            throw new FacesignException(R.ERROR, "找不到用户");
        }

        // 封装权限信息
        List<String> list = menuService.getAllPermsByUserId(user.getId());

        return new LoginUser(user, list);
    }
}
